package com.liang.hellocompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.navigation.*
import androidx.navigation.compose.*
import com.liang.hellocompose.data.HomeListEntity
import com.liang.hellocompose.net.ApiService
import com.liang.hellocompose.ui.theme.HelloComposeTheme
import com.liang.hellocompose.ui.theme.Purple500
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    private var result by mutableStateOf(HomeListEntity())
    private var index by mutableStateOf(0)
    private var currentTitle by mutableStateOf("Compose WanAndroid")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            HelloComposeTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    val navController = rememberNavController()
                    val backstackEntry = navController.currentBackStackEntryAsState()
                    val currentRoute = backstackEntry.value?.destination?.route
                    val scaffoldState = rememberScaffoldState()
                    val scope = rememberCoroutineScope()
                    Scaffold(scaffoldState = scaffoldState,
                        topBar = {
                            TopAppBar(
                                backgroundColor = Purple500,
                            ) {
                                if (currentRoute != "MainPage")
                                    IconButton(onClick = {
                                        navController.popBackStack()
                                    }) {
                                        Icon(
                                            imageVector = Icons.Filled.ArrowBack,
                                            contentDescription = ""
                                        )
                                    }
                                Text(text = currentTitle)
                            }
                        },
                        bottomBar = {
                            if (currentRoute == "MainPage")
                                BottomNavigation(backgroundColor = Color.White) {
                                    BottomNavigationItem(
                                        selected = index == 0,
                                        onClick = {
                                            requestData(0)
                                        },
                                        icon = {
                                            Icon(
                                                painter = painterResource(id = R.mipmap.ic_follow),
                                                contentDescription = null
                                            )
                                        },
                                        label = {
                                            Text(text = "首页")
                                        },
                                        selectedContentColor = Color.Blue,
                                        unselectedContentColor = Color.LightGray
                                    )
                                    BottomNavigationItem(
                                        selected = index == 1,
                                        onClick = {
                                            requestData(1)
                                        },
                                        icon = {
                                            Icon(
                                                painter = painterResource(id = R.mipmap.ic_followed),
                                                contentDescription = null
                                            )
                                        },
                                        label = {
                                            Text(text = "公众号")
                                        },
                                        selectedContentColor = Color.Blue,
                                        unselectedContentColor = Color.LightGray
                                    )
                                    BottomNavigationItem(
                                        selected = index == 2,
                                        onClick = {
                                            requestData(2)
                                        },
                                        icon = {
                                            Icon(
                                                painter = painterResource(id = R.mipmap.ic_follow),
                                                contentDescription = null
                                            )
                                        },
                                        label = {
                                            Text(text = "广场")
                                        },
                                        selectedContentColor = Color.Blue,
                                        unselectedContentColor = Color.LightGray
                                    )
                                    BottomNavigationItem(
                                        selected = index == 3,
                                        onClick = {
                                            requestData(3)
                                        },
                                        icon = {
                                            Icon(
                                                painter = painterResource(id = R.mipmap.ic_followed),
                                                contentDescription = null
                                            )
                                        },
                                        label = {
                                            Text(text = "我的")
                                        },
                                        selectedContentColor = Color.Blue,
                                        unselectedContentColor = Color.LightGray
                                    )
                                }
                        },
                        content = { paddingValues ->

                            NavHost(navController = navController, startDestination = "MainPage") {

                                composable("MainPage") {
                                    currentTitle = "MainPage"
                                    MainPage(
                                        navController,
                                        paddingValues,
                                        scaffoldState = scaffoldState,
                                        scope = scope
                                    )
                                }

                                composable(
                                    "SecondPage/{title}",
                                    arguments = listOf(navArgument("title") {
                                        type = NavType.StringType
                                    }),
                                    deepLinks = listOf(
                                        navDeepLink {
                                            uriPattern = "rally://MainPage/{title}"
                                        }
                                    )
                                ) {
                                    val title = it.arguments?.getString("title") ?: "Second Page"
                                    currentTitle = title
                                    SecondPage(
                                        paddingValues = paddingValues,
                                        navController,
                                        title
                                    )
                                }
                            }
                        }
                    )
                }
            }
        }
        requestData()
    }

    @Composable
    private fun MainPage(
        navController: NavHostController,
        pading: PaddingValues,
        scaffoldState: ScaffoldState,
        scope: CoroutineScope
    ) {
        when (index) {
            0 -> HomePageList(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(pading),
                homeListEntity = result,
                scaffoldState,
                scope,
                navController = navController
            )
            1 -> Greeting(name = "Second Page")
            2 -> Greeting(name = "Threed Page")
            3 -> HomePageList(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(pading),
                homeListEntity = result,
                scaffoldState,
                scope,
                navController = navController
            )
        }

    }

    @Composable
    fun BottomItem() {

    }

    private fun requestData(page: Int = 0) {
        index = page
        lifecycleScope.launchWhenCreated {
            val homeData = ApiService.wanAndroidApi.getHomeData(page)
            homeData.data?.let {
                result = it
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomePageList(
    modifier: Modifier,
    homeListEntity: HomeListEntity,
    scaffoldState: ScaffoldState,
    scope: CoroutineScope,
    navController: NavController
) {
    val state = LazyListState()
    LazyColumn(modifier = modifier, state = state) {

        val datas = homeListEntity.datas

        items(count = datas.size) { index ->
            val data = datas[index]
            Column {
                HomePageItem(data = data) {
                    navController.navigate(
                        "SecondPage/${data.title}"
                    )
                    navController.navigate("",)
                    scope.launch {
                        scaffoldState.snackbarHostState.showSnackbar(
                            message = data.title,
                            duration = SnackbarDuration.Short
                        )
                    }
                }
                Divider(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(1.dp), color = Color.LightGray
                )
            }
        }

    }

}

val navOptions = NavOptions.Builder()
    .setEnterAnim(R.anim.slide_in_right)
    .setExitAnim(R.anim.slide_in_left)
    .setPopEnterAnim(R.anim.slide_out_right)
    .setPopExitAnim(R.anim.slide_out_left)
    .build()

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    HelloComposeTheme {
        Greeting("Android")
    }
}